import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Tabs,
  Form,
  Table,
  Modal,
  Button,
  message,
} from 'antd';
import GeneralTableComponent from 'components/GeneralTableComponent';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import GeneralFilterComponent from 'components/GeneralFilterComponent';
import {env, host} from '../../utils/request';
import token from '../../utils/token';
import {sign} from '../../services/api';
import { stringify } from 'qs';

const TabPane = Tabs.TabPane;

@connect(({ totalList, loading }) => ({
  totalList,
  loading: loading.models.totalList,
}))
@Form.create()
export default class TotalList extends PureComponent {
  state = {
    paramList:{
      current: 1,
      pageSize: 10,
      userName: '',
      mobile: '',
      lendTime: '',   //放款时间
      repayTime: '',  //还款时间
      shallTime: '',  //应还日
      withdrawId: '',
    },
    detailDialogVisible: false,
  };

  componentDidMount() {
    this.getTotalData();
  }

  getTotalData = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let postParam = {}
    for (let [key, val] of Object.entries(paramList)) {
      if (val !== '' && key !== 'lendTime' && key !== 'repayTime' && key !== 'shallTime') {
        postParam[key] = val;
      }
    }
    if (paramList.lendTime[0]) {
       postParam.lendStartDate = paramList.lendTime[0].format('YYYY-MM-DD');
       postParam.lendEndDate = paramList.lendTime[1].format('YYYY-MM-DD');
    }
    if (paramList.repayTime[0]) {
       postParam.repayStartDate = paramList.repayTime[0].format('YYYY-MM-DD');
       postParam.repayEndDate = paramList.repayTime[1].format('YYYY-MM-DD');
    }
    if (paramList.shallTime[0]) {
       postParam.startDate = paramList.shallTime[0].format('YYYY-MM-DD');
       postParam.endDate = paramList.shallTime[1].format('YYYY-MM-DD');
    }
    console.log(postParam);
    dispatch({
      type: 'totalList/fetchQueryWithdrawBill',
      payload: {
        ...postParam
      }
    });
  };

  getDetail = (id) => {
    const { dispatch } = this.props;
    let postParam = {
      withdrawId: id
    }

    dispatch({
      type: 'totalList/fetchGetUserBankCardWithdraw',
      payload: {
        ...postParam
      }
    });
  };

  handleExport = () => {
    const { paramList } = this.state;
    let postParam = {}
    for (let [key, val] of Object.entries(paramList)) {
      if (val !== '' && key !== 'lendTime' && key !== 'repayTime' && key !== 'current' && key !== 'pageSize') {
        postParam[key] = val;
      }
    }
    if (paramList.lendTime[0]) {
       postParam.lendStartDate = paramList.lendTime[0].format('YYYY-MM-DD');
       postParam.lendEndDate = paramList.lendTime[1].format('YYYY-MM-DD');
    }
    if (paramList.repayTime[0]) {
       postParam.startDate = paramList.repayTime[0].format('YYYY-MM-DD');
       postParam.endDate = paramList.repayTime[1].format('YYYY-MM-DD');
    }
    console.log(postParam)
    //
    if (
      paramList.repayTime[0] ? paramList.repayTime[1].valueOf() - paramList.repayTime[0].valueOf() < 1000 * 60 * 60 * 24 * 90 : true &&
      paramList.lendTime[0] ? paramList.lendTime[1].valueOf() - paramList.lendTime[0].valueOf() < 1000 * 60 * 60 * 24 * 90 : true
    ) {
      var oReq = new XMLHttpRequest();
      oReq.open("GET", host[env] +'/bill/export/withdrawListExport'+'?'+`${stringify(postParam)}`+'&sign='+sign(postParam), true);
      oReq.responseType = "blob";
      oReq.setRequestHeader("Content-Type","application/json");
      oReq.setRequestHeader('Authorization',token.get());
      oReq.onload = function (oEvent) {console.log(oEvent)
        var content = oReq.response;
        var elink = document.createElement('a');
        elink.download = '总列表.xls';//xlsx    因为后台输入是scv格式，用xlsx显示的不理想
        elink.style.display = 'none';
        var blob = new Blob([content]);
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      };
      oReq.send(JSON.stringify(postParam));
    } else {
      message.error(`无法导出时间跨度大于90天的数据`);
    }

  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { paramList } = this.state;
    paramList.current = pagination.current;
    paramList.pageSize = pagination.pageSize;
    this.getTotalData();
  };

  handleFormReset = (value) => {
    const { paramList } = this.state;
    Object.assign(paramList, value);
    paramList.current = 1;
    this.getTotalData();
  };

  handleFormSearch = (value) => {
    const { paramList } = this.state;
    Object.assign(paramList, value);
    paramList.current = 1;
    this.getTotalData();
  };

  handleShowDetail = (row) => {
    this.getDetail(row.withdrawId);
    this.setState({
      detailDialogVisible: true
    });
  };

  handleDetailClose = () => {
    this.setState({
      detailDialogVisible: false
    });
  };

  formatDate(time) {
    if(time != '/') {
      let x = time - 0;

      let now = new Date(x);
      let year = now.getFullYear();
      let month = '0' + (now.getMonth() + 1);
      let date = '0' + now.getDate();
      let hour = '0' + now.getHours();
      let min = '0' + now.getMinutes();
      let second = '0' + now.getSeconds();
      return year + '-' + month.substr(-2) + '-' + date.substr(-2) + ' ' + hour.substr(-2) + ':' + min.substr(-2) + ':' + second.substr(-2);
    } else {
      return '/'
    }
  }

  render() {
    const { totalList: { totalListData, userBankCardData }, loading } = this.props;

    const tableColumns = [{
      title: '序号',
      dataIndex: 'demo',
      key: 'demo',
      render: (text, record, index) => {
        return <span>{index + 1 + ( totalListData.pagination.current - 1 ) * totalListData.pagination.size}</span>
      }
    }, {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      render: val => `${val}`
    }, {
      title: '订单号',
      dataIndex: 'withdrawId',
      key: 'withdrawId',
      render: val => `${val}`
    }, {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record, index) => {
        return <span>{ record.userName + ' ' + ( record.gender === "男" ? '♂' : ( record.gender === "女" ? '♀' : '' ) ) }</span>
      }
    }, {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      render: val => `${val}`
    }, {
      title: '放款时间',
      dataIndex: 'startTime',
      key: 'startTime',
      render: val => this.formatDate(val)
    }, {
      title: '应还日',
      dataIndex: 'endTime',
      key: 'endTime',
      render: val => this.formatDate(val)
    }, {
      title: '借款金额',
      dataIndex: 'withdrawAmount',
      key: 'withdrawAmount',
      render: val => `${val}`
    }, {
      title: '还款时间',
      dataIndex: 'repayTime',
      key: 'repayTime',
      render: val => this.formatDate(val)
    }, {
      title: '还款金额',
      dataIndex: 'repayAmount',
      key: 'repayAmount',
      render: val => `${val}`
    }, {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: val => `${val}`
    }, {
      title: '查看详情',
      dataIndex: 'demo2',
      key: 'demo2',
      render: (text, record, index) => {
        return <a href="javascript:;" onClick={() => this.handleShowDetail(record)}>查看详情</a>
      }
    }]

    const searchColumns = [{
      type: 'input',
      value: 'userName',
      label: '姓名',
      placeholder: '请输入',
    }, {
      type: 'input',
      value: 'mobile',
      label: '手机号',
      placeholder: '请输入',
    }, {
      type: 'rangePicker',
      value: 'lendTime',
      label: '放款时间',
      placeholder: ['起始时间', '结束时间'],
    }, {
      type: 'rangePicker',
      value: 'repayTime',
      label: '还款时间',
      placeholder: ['起始时间', '结束时间'],
    }, {
      type: 'rangePicker',
      value: 'shallTime',
      label: '应还日',
      placeholder: ['起始时间', '结束时间'],
    }, {
      type: 'input',
      value: 'withdrawId',
      label: '订单号',
      placeholder: '请输入',
    }];

    const detailColumns = [{
      title: '借款银行卡号',
      dataIndex: 'loanBankCardNum',
      key: '借款银行卡号',
      render: val => `${val ? val : '/'}`
    }, {
      title: '借款所需银行',
      dataIndex: 'loanBankName',
      key: 'loanBankName',
      render: val => `${val ? val : '/'}`
    }, {
      title: '还款银行卡号',
      dataIndex: 'repayBankCardNum',
      key: 'repayBankCardNum',
      render: val => `${val ? val : '/'}`
    }, {
      title: '还款所需银行',
      dataIndex: 'repayBankName',
      key: 'repayBankName',
      render: val => `${val ? val : '/'}`
    }]

    let detailData = [];
    detailData[0] = userBankCardData

    return (
      <PageHeaderLayout title="总订单列表">
        <Card bordered={false}>
          <div style={{marginBottom: 20}}>
            <GeneralFilterComponent
            itemList={searchColumns}
            onClear={this.handleFormReset}
            onSearch={this.handleFormSearch}
            ></GeneralFilterComponent>
          </div>

          <div style={{textAlign: 'right', marginBottom: 20}}>
            <Button icon="export" onClick={this.handleExport}>导出</Button>
          </div>

          <GeneralTableComponent
            loading={loading}
            data={totalListData}
            columns={tableColumns}
            onChange={this.handleStandardTableChange}
            showSizeChanger
          />
        </Card>

        <Modal
          title="查看详情"
          visible={this.state.detailDialogVisible}
          onOk={this.handleDetailClose}
          onCancel={this.handleDetailClose}
          width={'40%'}
        >
          <Table
          columns={detailColumns}
          dataSource={detailData}
          pagination={false}
          rowKey={record => parseInt(Math.random() * 10)}
          ></Table>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
